package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.entity.Employee;
import com.itheima.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){

        log.info("接收到用户登陆的信息：{}",employee);

        //1、将页面提交的密码password进行md5加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        log.info("加密后的密码：{}",password);
        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(employee.getUsername()!=null,Employee::getUsername,employee.getUsername());
        Employee one = employeeService.getOne(queryWrapper);

        //3、如果没有查询到则返回登录失败结果

        if (one == null){
            log.info("用户名不存在!");
            return R.error("登陆失败");
        }
        //4、密码比对，如果不一致则返回登录失败结果
        if (!one.getPassword().equals(password)){
            log.info("密码错误!");
            return R.error("登陆失败");
        }

        //5、查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if (one.getStatus()==0){
            log.info("账号已禁用!");
            return R.error("账号已被禁用");
        }

        //6、登录成功，将员工id存入Session并返回登录成功结果
        HttpSession session = request.getSession();
        session.setAttribute("empId",one.getId());
        return R.success(one);

    }

    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){

        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }


    @PostMapping
    public R<String> sqve(HttpSession session,@RequestBody Employee employee){

        log.info("emp{}",employee);
        employee.setStatus(1);
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes(StandardCharsets.UTF_8)));
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setCreateUser((Long) session.getAttribute("empId"));
//        employee.setUpdateUser((Long) session.getAttribute("empId"));

        boolean b = employeeService.save(employee);
        return b?R.success(null):R.error("新增失败");
    }

    @GetMapping("/page")
    public R page(Integer page,Integer pageSize,String name){
        log.info("page{},pageSize:{},name:{}",page,pageSize,name);
        IPage<Employee> employeeIPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name!=null,Employee::getName,name);
        wrapper.orderByAsc(Employee::getUpdateTime);
        employeeService.page(employeeIPage,wrapper);
        return R.success(employeeIPage);
    }

    @PutMapping
    public R update(HttpSession session,@RequestBody Employee employee){
//        log.info("修改的emp为：{}",employee);
//        employee.setUpdateUser((long)session.getAttribute("empId"));
//        employee.setUpdateTime(LocalDateTime.now());
        boolean b = employeeService.updateById(employee);

        return b?R.success("操作成功"):R.error("操作失误");
    }


    @GetMapping("/{id}")
    private R getById(@PathVariable Long id){
        log.info("id:{}",id);
        Employee employee = employeeService.getById(id);
        return R.success(employee);
    }


}
